import { Component, createEffect, createSignal } from 'solid-js';
import { useSearchParams } from '@solidjs/router';
import { searchAllApps } from '@/lib/api/app';
import { AppItem } from '@/types/app';
import AppList from '@/components/AppList';

const Search: Component = () => {
  const [searchParams] = useSearchParams();
  const [searchResults, setSearchResults] = createSignal<AppItem[]>([]);
  const [loading, setLoading] = createSignal(true);
  const [error, setError] = createSignal<string | null>(null);

  createEffect(async () => {
    const query = searchParams.q;
    if (query && typeof query === 'string') {
      setLoading(true);
      setError(null);
      try {
        const results = await searchAllApps(query);
        setSearchResults(results);
      } catch (err) {
        setError(err instanceof Error ? err.message : '搜索失败');
      } finally {
        setLoading(false);
      }
    }
  });

  return (
    <div class="p-6 w-full h-full">
      <h1 class="text-2xl font-bold mb-6">
        搜索结果: {searchParams.q}
      </h1>
      {error() ? (
        <div class="text-red-500">{error()}</div>
      ) : (
        <AppList
          apps={searchResults()}
          loading={loading()}
        />
      )}
    </div>
  );
};

export default Search;